/*
 * Copyright 2012-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pipi.controller;

import com.sun.media.sound.ModelDirectedPlayer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Map;

@Controller
public class WelcomeController {

	@Value("${application.message:Hello World}")
	private String message = "Hello World";

	@Value("${weather.uploadFilePath}")
	String uploadFilePath;

	@RequestMapping(value = "/" ,method = RequestMethod.GET)
	public String welcome(Map<String, Object> model, HttpSession session) {
//		System.out.println(session.getAttribute("test").toString());
		model.put("time", new Date());
		model.put("message", this.message);
		return "welcome";
	}

	@RequestMapping("/foo")
	public String foo(Map<String, Object> model) {
		throw new RuntimeException("Foo");
	}

	@GetMapping("/session")
	@ResponseBody
	public String getSessionId(HttpSession session) {
		return session.getId();
	}

	@RequestMapping(value = "/toplay", method = RequestMethod.GET)
	public String toPaly(Model model) {

		File dir = new File(uploadFilePath);
		File music = dir.listFiles()[0].listFiles()[0];
		String fileName = music.getName();
		model.addAttribute("fileName",fileName);
		return "audio";
	}

	@RequestMapping(value = "/play/{filename}", method = RequestMethod.GET)
	public void  audioPlay(HttpServletResponse httpResponse, @PathVariable("filename") String fileName) throws Exception{
		File dir = new File(uploadFilePath);
		File music = dir.listFiles()[0].listFiles()[0];
		FileInputStream inputStream = new FileInputStream(music);

		httpResponse.setContentType("audio/mp3");
		OutputStream out = httpResponse.getOutputStream();

		int b = 0;
		byte[] buffer = new byte[1024];
		while ((b = inputStream.read(buffer)) != -1) {
			// 4.写到输出流(out)中
			out.write(buffer, 0, b);
		}
		inputStream.close();
		out.flush();
		out.close();
		return;

	}


	@GetMapping("/to_upload")
	public String getUpload(){

		return "fileupload";
	}

	@PostMapping("/uploadfile")
	public String upload(){

		return "ok";

	}

}
